package com.hula.onion.book.server.spider.platforms.tuandai;

import com.alibaba.fastjson.JSONObject;
import com.hula.onion.book.server.common.CommonResponse;
import com.hula.onion.book.server.common.SpiderCommon;
import com.hula.onion.book.server.config.ResponseStatusEnum;
import com.hula.onion.book.server.utils.DateUtils;
import com.hula.onion.book.server.utils.HttpUtils;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * Description:团贷spider
 * Create Date:2018/1/17 19:33
 *
 * @author liangbing
 * @version 1.0
 */
@Component("tuanDaiSpider")
public class TuanDaiSpider extends SpiderCommon {

    /**
     * 获取RSA key url
     */
    private static final String GET_RSA_KEY_URL = "https://passport.tuandai.com/generatorKey?t=";
    /**
     * 登录URL
     */
    private static final String LOGIN_URL = "https://passport.tuandai.com/2login";
    /**
     * 获取账户信息URL
     */
    private static final String GET_ACCOUNT_INFO_URL = "https://www.tuandai.com/member/account_default.aspx";

    /**
     * 获取收益信息
     */
    private static final String INTEREST_INFO = "https://www.tuandai.com/member/account_default_profit.aspx";

    @Autowired
    private TuanDaiSpiderHelper tuanDaiSpiderHelper;

    /**
     * 执行爬取操作
     * 1.获取 RSA key
     * 2.组装模拟登陆参数，模拟登陆
     * 3.爬取用户详细信息
     */
    @Override
    public CommonResponse execute() {

        CommonResponse commonResponse = new CommonResponse(ResponseStatusEnum.FAIL);

        //1.获取 RSA key
        long t = DateUtils.getCurrentMillisecond();

        BasicClientCookie cookie = new BasicClientCookie("tDLgk", "c2617a5ef03543d7aff9666556e9176b6ct025");
        cookie.setVersion(0);
        cookie.setDomain(".passport.tuandai.com");
        cookie.setPath("/");
        getHttpContext().getCookieStore().addCookie(cookie);
        String rsaKey = HttpUtils.get(GET_RSA_KEY_URL + t, getHttpContext());

        if (!StringUtils.isEmpty(rsaKey)) {
            //2.1 组装模拟登陆参数
            try {
                //2.2 模拟登陆
                String responseStr = HttpUtils.post(LOGIN_URL,
                        tuanDaiSpiderHelper.installRequestParams(loginForm, rsaKey),
                        getHttpContext());
                TuanDaiResponseEntity responseEntity = JSONObject.parseObject(responseStr, TuanDaiResponseEntity.class);

                logger.info("[LuJinSuoSpider] Http response result:{}", responseEntity.toString());

                if (responseEntity.isSuccess()) {
                    //3.1 爬取用户详细信息
                    String accountHtml = HttpUtils.get(GET_ACCOUNT_INFO_URL, getHttpContext());
                    //3.2 爬去用户收益信息
                    String interestHtml = HttpUtils.get(INTEREST_INFO, getHttpContext());
                    //3.3 解析html
                    return tuanDaiSpiderHelper.parseAccountBalance(accountHtml,interestHtml);
                } else {
                    if (!StringUtils.isEmpty(responseEntity.getCaptchaJsURL())) {
                        commonResponse.setData(responseEntity.getCaptchaJsURL());
                    }
                    commonResponse.setMsg(responseEntity.getErrorMsg());
                    commonResponse.setCode(responseEntity.getErrorCode());
                }

            } catch (Exception e) {
                logger.error("[LuJinSuoSpider] Install request params error!");
            }
        } else {
            logger.error("[LuJinSuoSpider] Http get RSA key failed! ");
        }

        return commonResponse;
    }
}
